<?
use Swoole\Timer;

function wait($v=0)
{
    \Swoole\Coroutine\System::sleep((float)$v);
}

function loger($v = '')
{
    $t=explode(' ', date('Y-m-d H:i:s'));
    if (is_array($v) || is_object($v)) {
        $v = print_r($v, true);
    }
    echo shell_exec('echo -n "[' . $t[1] . '] "') . $v . PHP_EOL;
}

function tu($fn, $value = '')
{
    $s = microtime(true);
    $fn();
    $u = intval((microtime(true) - $s) * 1000);
    loger($value . '耗时:' . $u . '毫秒');
}

function apiErr($value='',$code=300)
{
    throw new \core\Err((string)$value, (int)$code);
}

function app()
{
    $o = func_get_args();
    $key=array_shift($o);
    switch ($key) {
        case 'curr':
            return \Swoole\Coroutine::getContext();
        case 'user':
            if (!$token = \Swoole\Coroutine::getContext()->request->header['authorization']??null) {
                return null;
            }

            if (!$res = token(substr($token, 7),true)??[]) {
                return null;
            }

            return (object)$res;
        case 'redis':
            if (!$connect = array_shift($o)) {
                return \core\Db\Redis::class;
            }
            // \core\Db\Redis::u($connect);
            return \core\Db\Redis::u($connect);
        case 'task':
            return new \core\Task;
        case 'http':
            return \core\Http::url(...$o);
        case 'sendfile':
            if (!$file = array_shift($o)) {
                return;
            }
            $fi = BASE_PATH.'/runtime/'.$file;
            $response=app('curr')->response;
            $response->header('Content-Type', mime_content_type($fi));
            return $response->sendfile($fi);
        default:
            break;
    }
}


function env($key='',$default='')
{
    $r=getenv($key);
    return $r?$r:$default;
}


function config($key='')
{
    if (!$key) {
        return $GLOBALS['config'];
    }
    if (strpos($key,'.')===false) {
        return $GLOBALS['config'][$key]??null;
    }
    
    $keys = explode('.',$key);
    $curr = $GLOBALS['config'];
    foreach ($keys as $k) {
        $curr = $curr[$k]??null;
    }

    return $curr;
}

function json($data=[],$message='请求成功',$code=0)
{
    $result=['code'=>$code,'message'=>$message,'data'=>$data];
    $response = app('curr')->response;    

    $response->header('Access-Control-Allow-Origin', '*');
    $response->header('Access-Control-Allow-Methods', '*');
    $response->header('Access-Control-Allow-Headers', '*');
    $response->header('Content-Type', 'application/json;charset=utf-8');

    if ($response->isWritable()) {
        return $response->end(json_encode($result));
    }
}

function m($model='')
{
    if (!$config = config('model.'.$model)) {
        apiErr('模型不存在');
    }

    $class= '\\app\\model\\'.ucfirst($model);
    $handler = new $class;
    $handler->query['table'] = $config['table'];
    $handler->config = $config;
    $handler->apiData = app('curr')->data??[];
    return $handler;
}

function token($data = '', $de = false)
{
    if ($de) {
        if (! $ret = openssl_decrypt(base64_decode($data), 'AES-128-CBC', 'service.yuwan.cn', 1, 'service.yuwan.cn')) {
            return null;
        }
        return json_decode($ret, true);
    }

    if (is_array($data)||is_object($data)) {
        $data = json_encode($data);
    }

    return base64_encode(openssl_encrypt((string) $data, 'AES-128-CBC', 'service.yuwan.cn', 1, 'service.yuwan.cn'));
}